package com.ruoyi.merchant.service.impl;

import com.ruoyi.common.exception.ServiceException;

import com.ruoyi.merchant.domain.Order;
import com.ruoyi.merchant.domain.OrderItem;
import com.ruoyi.merchant.domain.MerchantPrinter;
import com.ruoyi.merchant.domain.dto.OrderCancelDTO;
import com.ruoyi.merchant.domain.dto.OrderQueryDTO;
import com.ruoyi.merchant.mapper.OrderMapper;
import com.ruoyi.merchant.mapper.OrderItemMapper;
import com.ruoyi.merchant.mapper.MerchantPrinterMapper;
import com.ruoyi.merchant.mapper.UserMapper;
import com.ruoyi.merchant.service.IOrderService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * 订单Service业务层处理
 */
@Service
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private MerchantPrinterMapper printerMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Order selectOrderByOrderId(Long orderId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!merchantId.equals(order.getMerchantId())) {
            throw new ServiceException("无权访问该订单");
        }

        // 加载订单明细
        List<OrderItem> items = orderItemMapper.selectByOrderId(orderId);
        order.setItems(items);

        // 🔥 加载用户信息（昵称、手机号、区域ID）
        try {
            Map<String, Object> userInfo = userMapper.selectUserBasicInfo(order.getCustomerId());
            if (userInfo != null) {
                order.setCustomerNickname((String) userInfo.get("nickname"));
                order.setCustomerPhone((String) userInfo.get("phone_number"));
                order.setCustomerRegionId(userInfo.get("region_id") != null
                        ? ((Number) userInfo.get("region_id")).longValue()
                        : null);
            }
        } catch (Exception e) {
            log.error("加载用户信息失败：customerId={}", order.getCustomerId(), e);
            // 用户信息加载失败不影响订单查询
        }

        return order;
    }

    @Override
    public List<Order> selectOrderList(OrderQueryDTO queryDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        List<Order> orders = orderMapper.selectMerchantOrderList(
            merchantId,
            queryDTO.getStatus(),
            queryDTO.getPaymentStatus(),
            queryDTO.getOrderNo(),
            queryDTO.getPickupCode(),
            queryDTO.getStartTime(),
            queryDTO.getEndTime()
        );

        // 批量加载订单明细（优化性能）
        if (!orders.isEmpty()) {
            List<Long> orderIds = orders.stream()
                .map(Order::getOrderId)
                .collect(java.util.stream.Collectors.toList());
            
            List<OrderItem> allItems = orderItemMapper.selectByOrderIds(orderIds);
            
            // 按订单ID分组
            Map<Long, List<OrderItem>> itemsMap = allItems.stream()
                .collect(java.util.stream.Collectors.groupingBy(OrderItem::getOrderId));
            
            // 设置每个订单的明细
            orders.forEach(order -> {
                order.setItems(itemsMap.getOrDefault(order.getOrderId(), java.util.Collections.emptyList()));
            });
        }

        return orders;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int acceptOrder(Long orderId, Integer estimatedMin) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 验证订单
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!merchantId.equals(order.getMerchantId())) {
            throw new ServiceException("无权操作该订单");
        }
        if (order.getStatus() != 0) {
            throw new ServiceException("订单状态不正确，无法接单");
        }
        if (order.getPaymentStatus() != 1) {
            throw new ServiceException("订单未支付，无法接单");
        }

        // 更新订单状态
        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setMerchantId(merchantId);
        updateOrder.setStatus(1);
        updateOrder.setEstimatedReadyMin(estimatedMin);

        int result = orderMapper.updateOrder(updateOrder);

        // 自动打印订单（如果有默认打印机且开启自动打印）
        if (result > 0) {
            autoPrintOrder(orderId);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int batchAcceptOrders(Long[] orderIds, Integer estimatedMin) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();

        // 验证所有订单
        for (Long orderId : orderIds) {
            Order order = orderMapper.selectOrderByOrderId(orderId);
            if (order == null || !merchantId.equals(order.getMerchantId())) {
                throw new ServiceException("包含无权操作的订单");
            }
            if (order.getStatus() != 0) {
                throw new ServiceException("订单【" + order.getOrderNo() + "】状态不正确，无法接单");
            }
            if (order.getPaymentStatus() != 1) {
                throw new ServiceException("订单【" + order.getOrderNo() + "】未支付，无法接单");
            }
        }

        // 🔥 批量更新（传入预计完成时间）
        int result = orderMapper.batchUpdateOrderStatus(orderIds, 1, estimatedMin, merchantId);

        // 批量打印订单
        for (Long orderId : orderIds) {
            autoPrintOrder(orderId);
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int startMaking(Long orderId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!merchantId.equals(order.getMerchantId())) {
            throw new ServiceException("无权操作该订单");
        }
        if (order.getStatus() != 1) {
            throw new ServiceException("订单状态不正确，无法开始制作");
        }

        return orderMapper.updateOrderStatus(orderId, 2, merchantId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int orderReady(Long orderId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!merchantId.equals(order.getMerchantId())) {
            throw new ServiceException("无权操作该订单");
        }
        if (order.getStatus() != 2) {
            throw new ServiceException("订单状态不正确，无法标记为待取餐");
        }

        return orderMapper.updateOrderStatus(orderId, 3, merchantId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int completeOrder(Long orderId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!merchantId.equals(order.getMerchantId())) {
            throw new ServiceException("无权操作该订单");
        }
        if (order.getStatus() != 3) {
            throw new ServiceException("订单状态不正确，无法完成订单");
        }

        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setMerchantId(merchantId);
        updateOrder.setStatus(4);
        updateOrder.setFinishedAt(new Date());

        return orderMapper.updateOrder(updateOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelOrder(OrderCancelDTO cancelDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        Long orderId = cancelDTO.getOrderId();
        
        Order order = orderMapper.selectOrderByOrderId(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!merchantId.equals(order.getMerchantId())) {
            throw new ServiceException("无权操作该订单");
        }
        if (order.getStatus() == 4) {
            throw new ServiceException("订单已完成，无法取消");
        }
        if (order.getStatus() == 5) {
            throw new ServiceException("订单已取消");
        }

        Order updateOrder = new Order();
        updateOrder.setOrderId(orderId);
        updateOrder.setMerchantId(merchantId);
        updateOrder.setStatus(5);
        updateOrder.setCanceledAt(new Date());
        updateOrder.setExternField1(cancelDTO.getCancelReason()); // 存储取消原因

        // TODO: 如果订单已支付，需要触发退款流程

        return orderMapper.updateOrder(updateOrder);
    }

    @Override
    public Map<String, Object> countOrderByStatus() {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        return orderMapper.countOrderByStatus(merchantId);
    }

    @Override
    public Map<String, Object> getTodaySummary() {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        return orderMapper.countTodayOrders(merchantId);
    }

    @Override
    public Map<String, Object> getOrderAmountStatistics(String startTime, String endTime) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        return orderMapper.sumOrderAmount(merchantId, startTime, endTime);
    }

    @Override
    public int printOrder(Long orderId, Long printerId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        
        // 验证订单
        Order order = selectOrderByOrderId(orderId);
        
        // 获取打印机
        MerchantPrinter printer;
        if (printerId != null) {
            printer = printerMapper.selectPrinterByPrinterId(printerId);
            if (printer == null || !merchantId.equals(printer.getMerchantId())) {
                throw new ServiceException("打印机不存在或无权使用");
            }
        } else {
            printer = printerMapper.selectDefaultPrinter(merchantId);
            if (printer == null) {
                throw new ServiceException("未设置默认打印机");
            }
        }

        if (printer.getStatus() != 1) {
            throw new ServiceException("打印机未启用");
        }

        // TODO: 调用打印机SDK进行打印
        // 这里需要根据打印机品牌（飞鹅、易联云等）调用不同的API
        return doPrint(order, printer);
    }

    /**
     * 自动打印订单
     */
    private void autoPrintOrder(Long orderId) {
        try {
            Long merchantId = MerchantSecurityUtils.getMerchantId();
            MerchantPrinter printer = printerMapper.selectDefaultPrinter(merchantId);
            
            if (printer != null && printer.getAutoPrintOrder() == 1 && printer.getStatus() == 1) {
                printOrder(orderId, printer.getPrinterId());
            }
        } catch (Exception e) {
            // 打印失败不影响接单流程，记录日志即可
            // log.error("自动打印订单失败", e);
        }
    }

    /**
     * 执行打印
     */
    private int doPrint(Order order, MerchantPrinter printer) {
        // 构建打印内容
        String content = buildPrintContent(order, printer.getPrintWidth());
        
        // 根据打印机品牌调用不同的API
        switch (printer.getPrinterBrand().toLowerCase()) {
            case "feie":
                // 调用飞鹅云打印API
                return printByFeie(printer, content);
            case "yilianyun":
                // 调用易联云API
                return printByYilianyun(printer, content);
            default:
                throw new ServiceException("不支持的打印机品牌：" + printer.getPrinterBrand());
        }
    }

    /**
     * 构建打印内容
     */
    private String buildPrintContent(Order order, int width) {
        StringBuilder sb = new StringBuilder();
        String line = width == 58 ? "--------------------------------" : "------------------------------------------------";
        
        sb.append("<CB>取餐号：").append(order.getPickupCode()).append("</CB>\n");
        sb.append(line).append("\n");
        sb.append("订单号：").append(order.getOrderNo()).append("\n");
        sb.append("下单时间：").append(order.getCreatedAt()).append("\n");
        sb.append(line).append("\n");
        
        // 商品明细
        sb.append("<B>商品</B>").append("         ").append("数量").append("   ").append("金额\n");
        for (OrderItem item : order.getItems()) {
            sb.append(item.getProductName()).append("\n");
            if (item.getTasteOptions() != null && !item.getTasteOptions().isEmpty()) {
                sb.append("  规格：").append(item.getTasteOptions()).append("\n");
            }
            sb.append("  ").append("x").append(item.getQuantity())
              .append("   ¥").append(item.getTotalPrice()).append("\n");
        }
        
        sb.append(line).append("\n");
        sb.append("商品总额：¥").append(order.getTotalAmount()).append("\n");
        if (order.getDiscountAmount().compareTo(java.math.BigDecimal.ZERO) > 0) {
            sb.append("优惠金额：-¥").append(order.getDiscountAmount()).append("\n");
        }
        sb.append("<B>实付金额：¥").append(order.getFinalAmount()).append("</B>\n");
        sb.append(line).append("\n");
        
        if (order.getRemark() != null && !order.getRemark().isEmpty()) {
            sb.append("<B>备注：").append(order.getRemark()).append("</B>\n");
            sb.append(line).append("\n");
        }
        
        sb.append("餐具：").append(order.getTablewareCount()).append("份\n");
        sb.append("\n\n\n");
        
        return sb.toString();
    }

    /**
     * 飞鹅云打印
     */
    private int printByFeie(MerchantPrinter printer, String content) {
        // TODO: 实现飞鹅云打印API调用
        // https://www.feieyun.com/open/index.html
        return 1;
    }

    /**
     * 易联云打印
     */
    private int printByYilianyun(MerchantPrinter printer, String content) {
        // TODO: 实现易联云打印API调用
        // https://www.yilianyun.com/
        return 1;
    }
}
